# Title     : TODO
# Objective : TODO
# Created by: yz
# Created on: 2018/3/1

library(optparse)
library(magrittr)
library(tidyr)
library(tibble)
library(tidyverse)

option_list <- list(
  make_option("--d", type = 'character', action = "store", default = "./", help = "the database direcotry"),
  make_option("--base", default = "metabo_base.R", type = "character", help = "metabo base R file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--config", default = "calculate_config.json", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

configJson <- fromJSON(opt$config)

method <- configJson$method
nodeImp <- configJson$nodeImp
species <- configJson$species
isSmp <- configJson$isSmp

library <- if (isSmp == "kegg") {
  species
}else str_c(species, "-smpdb", sep = "")

hasSmp <- if (isSmp == "kegg") {
  FALSE
}else TRUE

fcData <- read_tsv("fc_color.txt")

if (nrow(fcData) == 0) {
  quit(status = 0)
}

diffData <- read_csv("AllMet_with_Anno.csv") %>%
  rowwise() %>%
  do({
    result <- as_tibble(.)
    id <- result[1, "KEGG"]
    metabolite <- result[1, "Metabolite"]
    ids <- str_split(id, "/") %>% unlist()
    metabolites <- str_split(metabolite, "/") %>% unlist()
    ids %>%
      map2_dfr(metabolites, function(id, metabolite) {
        result %>%
          mutate(KEGG = id, Metabolite = metabolite)
      })
  }) %>%
  ungroup()

diffData

load("idMapping_mSet.RData")
libs <- unlist(strsplit(library, "-"))
# library<-"hsa_new2"
if (length(libs) > 1) {
  mSet <- SetSMPDB.PathLib(mSet, libs[1], dataDir = opt$d)
  mSet <- SetOrganism(mSet, libs[1])
}else {
  mSet <- SetKEGG.PathLib(mSet, library, dataDir = opt$d)
}
mSet <- SetMetabolomeFilter(mSet, F)
mSet <- CalculateOraScore(mSet, nodeImp, method, dataDir = opt$d, fcData = fcData, hasSmp, diffData = diffData)
save(mSet, metpa, file = "kegg_enrich.RData")



